<template>
  <div class="project-roles-page">
    <div class="main">
      <div class="header">
        <p class="title">项目角色</p>
        <div class="search-container">
          <div class="search-input">
            <h4>{{ roleInfo.roleName || '' }}</h4>
          </div>
          <div class="btns">
            <el-button @click="back">
              取消
            </el-button>
            <el-button v-if="hasTabSet" type="primary" :loading="loading" @click="handleSave">
              授权
            </el-button>
          </div>
        </div>
      </div>
      <div class="table-container">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          row-key="id">
          <el-table-column prop="select" width="100">
            <template slot="header" slot-scope="scope">
              <el-checkbox
                :value="hasSelected"
                @change="selectAll">
              </el-checkbox>
            </template>
            <template slot-scope="scope">
              <el-checkbox
                :value="scope.row.isSelected"
                @change="(val) => handleChange(val, scope.row)">
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" width="80"></el-table-column>
          <el-table-column prop="name" label="菜单名称"></el-table-column>
          <el-table-column prop="path" label="地址"></el-table-column>
          <el-table-column prop="type" label="类型">
            <template slot-scope="scope">
              {{ types[scope.row.type] || '' }}
            </template>
          </el-table-column>
          <div class="empty-content" slot="empty">
            <i class="iconfont iconwushuju"></i>
            <p>暂无数据</p>
          </div>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleId: '',
      roleInfo: {},
      hasSelected: true,
      selectIds: [],
      tableIds: [],
      loading: false,
      menuTypes: [],
      classId: '',
      tableData: [],
      tableLoading: false,
      types: {
        '0': '目录',
        '1': '菜单',
        '2': '按钮'
      },
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    }
  },
  async created() {
    const { roleId } = this.$route.query;
    this.roleId = roleId || '';
    this.getRoleInfoById();
    await this.getRolePermissionTree();
    this.getProjectTree();
  },
  methods: {
    /**
     * 获取角色详情
     */
    async getRoleInfoById() {
      const { success, data: {
        data
      }} = await this.$Model.getRoleInfoById({
        id: this.roleId,
      });
      if (success && data) {
        this.roleInfo = data;
      }
    },
    /**
     * 获取角色菜单权限
     */
    async getRolePermissionTree() {
      if (!this.roleId) return;
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getRolePermissionTree({
        id: this.roleId
      });
      this.tableLoading = false;
      if (success && data) {
        this.selectIds = this.getSelectKeys(data);
      }
    },
    /**
     * 获取项目菜单权限
     */
    async getProjectTree() {
      if (!this.projectId) return;
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getProjectTree({
        id: this.projectId
      });
      this.tableLoading = false;
      if (success && data) {
        this.tableData = this.setMenuTree(data);
      }
    },
    /**
     * 获取当前角色的权限ID
     * @param {Array} data
     * @param {Array} keys
     */
    getSelectKeys(data = [], keys = []) {
      const result = keys;
      data && data.forEach(item => {
        const { children, isCheck, id } = item;
        if (isCheck === '1') result.push(id);
        if (children && children.length) {
          this.getSelectKeys(children, result);
        }
      });
      return result;
    },
    /**
     * 设置当前菜单
     */
    setMenuTree(data, list = []) {
      const result = list;
      data && data.forEach(item => {
        const { children, isCheck, id } = item;
        const isSelected = this.selectIds.includes(id);
        const options = {
          ...item,
          isSelected,
          children: []
        };
        if (isCheck === '1') {
          if (!isSelected) this.hasSelected = false;
          result.push(options);
          this.tableIds.push(id);
          if (Array.isArray(children) && children.length) {
            options.children = this.setMenuTree(children, options.children);
          }
        }
      });
      return result;
    },
    checkId(id) {
      return this.selectIds.includes(id);
    },
    // 校验全选
    checkAll() {
      this.hasSelected = this.tableIds.every(id => (
        this.selectIds.includes(id)
      ));
    },
    /**
     * 设置菜单勾选状态
     * @param {Array} data 当前菜单数据
     * @param {?Boolean} selected 是否全选
     */
    setTreeData(data = [], selected = false) {
      return data && data.map(item => {
        const { children, id } = item;
        selected && this.selectIds.push(id);
        return {
          ...item,
          isSelected: selected || this.checkId(id),
          children: this.setTreeData(children, selected)
        };
      }) || [];
    },
    // 全选
    selectAll(hasCheck) {
      this.hasSelected = hasCheck;
      this.selectIds = [];
      this.tableData = this.setTreeData(this.tableData, hasCheck);
    },
    handleChange(hasCheck, row) {
      const { id } = row;
      const index = this.selectIds.indexOf(id);
      if (hasCheck) {
        index < 0 && this.selectIds.push(id);
      } else {
        index > -1 && this.selectIds.splice(index, 1);
      }
      if (!hasCheck) this.hasSelected = false;
      else this.checkAll();
      this.tableData = this.setTreeData(this.tableData);
    },
    // 授权
    async handleSave() {
      if (!this.roleId) return;
      this.loading = true;
      const { success } = await this.$Model.setRolePermissions({
        roleId: this.roleId,
        sysRolePermissions: this.selectIds.map(id => ({
          menuId: id,
          roleId: this.roleId
        }))
      });
      this.loading = false;
      if (success) {
        this.$message.success('授权成功');
      }
    },
    // 取消
    back() {
      this.$store.commit('updateTabId', '2');
      this.$router.back();
    }
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";

  .project-roles-page {
    width: 100%;
    height: 100%;
    padding: 20px 30px;
    background-color: $baseBg;
    .main {
      width: 100%;
      height: 100%;
      padding: 20px;
      background-color: $mainBg;
      .header {
        width: 100%;
        height: 100px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-bottom: 20px;
        .title {
          font-size: 20px;
        }
        .search-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .search-input {
            display: flex;
          }
        }
      }
      .table-container {
        width: 100%;
        height: calc(100% - 100px);
        /deep/ .el-table {
          height: calc(100% - 50px);
          .el-table__body-wrapper {
            height: calc(100% - 40px);
            overflow-y: auto;
            .btn {
              color: $mainColor;
              cursor: pointer;
              &:hover {
                text-decoration: underline;
              }
            }
          }
        }
      }
    }
  }
</style>
